import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/getPageTitle'
//避免重复点击报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

import LayOut from '@/layOut/index'
import userCenter from './modules/userCenter'
import charts from './modules/charts'

const Login = () => import(/* webpackChunkName: "users" */ '@/pages/login/login.vue')
const Register = () => import(/* webpackChunkName: "users" */ '@/pages/register/register.vue')
const Page404 = () => import(/* webpackChunkName: "user404" */ '@/pages/404/404.vue')

export const constantRoute=[
  {
    path: '/login',
    component: Login,
    hidden: true,
    name:'login'
  },

  {
    path: '/register',
    component: Register,
    hidden: true,
    name:'register'
  },
  {
    path: '/404',
    component: Page404,
    hidden: true,
    name:'404'
  },
  userCenter,
  charts,
  {
    path: '/',
    component: LayOut,
    name:'主页'
  },
]
const router= new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoute
})

router.beforeEach(async(to,from,next)=>{

  document.title =getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasRoles = store.getters["user/roles"] && store.getters["user/roles"].length > 0
      if (hasRoles) {
        next()
      } else {
          try {
            
            const { roles } = await store.dispatch('user/getInfo')
            const accessRoutes = await store.dispatch('routers/generateRoutes', roles)
            router.addRoutes(accessRoutes)
            next({ ...to, replace: true })
          } catch (error) {
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
          }

      }
    }
  }else{
//
next()
  }
  next()
})
export default router